//-------------------------------------------------------------------------------------
//autostats
function autostats()
{
	var headerlinks = document.evaluate("//a[@class='header_link']",document,null,XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,null);
	var statslink = headerlinks.snapshotItem(2).innerHTML;
	var statspan = headerlinks.snapshotItem(2).getElementsByTagName('span');
	if (statspan.length>0) {
		//Statpoints available
		var statpoints=parseInt(statspan[0].innerHTML.replace('(','').replace(')',''));
		var statToUpgrade=GM_getValue('statUpgrade','');
		var statneed=(statToUpgrade=='max_stamina') ? 2 : 1;
		//quotient = ( numerator - (numerator % denominator) ) / denominator
		var timesupgrade = ((statpoints - (statpoints % statneed)) / statneed);
		if ((statpoints>=statneed) && (location.href.indexOf('stats.php')==-1)) {
			addToLog(statpoints+' Stat points available. Upgrading '+statToUpgrade+' '+timesupgrade+' times.');
			//http://apps.facebook.com/piratesrule/stats.php?type=attack&action=Increase
			document.location = 'http://apps.facebook.com/'+SCRIPT.name+'/stats.php?type='+statToUpgrade+'&action=Increase';
		}
	}
	
	if (location.href.indexOf('stats.php')!=-1) {
		//Log statsupgrades
		var msg = document.evaluate("//span[@class='message_body']",document,null,9,null).singleNodeValue;
		if (msg!=null) {
			if (msg.innerHTML.indexOf('Ye just upgraded')!=-1) {
				//Ye just upgraded yer Maximum Energy by 1.
				addToLog(msg.innerHTML.replace('Ye just upgraded','Upgraded'));
			}
		}
		
		if (statpoints>=statneed) {
		//Do more statsupgrades if points available.
			document.location = 'http://apps.facebook.com/'+SCRIPT.name+'/stats.php?type='+statToUpgrade+'&action=Increase';
		} else {
			//no more statpoints available, return to index.
			document.location = 'http://apps.facebook.com/'+SCRIPT.name+'/index.php';
		}
	}
}
